import fetch from 'dva/fetch';
import { notification } from 'antd';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}
function setGetUrl(url, body) {
  if (!body) return url
  Object.keys(body).map((k, i) => {
    let p = i === 0 ? '?' : '&'
    url += `${p}${k}=${body[k]}`
  })
  return url
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const newOptions = { ...options }
  if (
    newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE'
  ) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        ...newOptions.headers,
      };
      newOptions.body = JSON.stringify(newOptions.body);
    } else {
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
      }
    }
  }
  if (newOptions.method === 'GET' && newOptions.body) {
    url = setGetUrl(url, newOptions.body)
    delete newOptions.body
  }
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => data)
    .then(data => {
      const { data: _, msg, code  } = data
      if (code !== 200) {
        const error = new Error(msg || '系统错误');
        error.data = data;
        throw error;
      }
      return _
    })
    .catch(err => {
      notification.error({
        message: '错误',
        description: err.message
      });
      return err
    });
}
